package com.springboot.jwt.exception;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义异常处理（全局异常处理）
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的业务异常
     * @param request
     * @param bizException
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public ResultResponse bizExceptionHandler(HttpServletRequest request, BizException bizException)
    {
        logger.error("发生业务异常, 原因是: {}", bizException.getErrorMsg());
        return ResultResponse.error(bizException.getErrorCode(), bizException.getMessage());
    }

    /**
     * 处理空指针异常
     * @param request
     * @param nullPointerException
     * @return
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public ResultResponse exceptionHandler(HttpServletRequest request, NullPointerException nullPointerException)
    {
        logger.error("发生空指针异常, 原因是: ", nullPointerException);
        return ResultResponse.error(ExceptionEnum.BODY_NOT_MATCH);
    }

    @ExceptionHandler(value = NumberFormatException.class)
    @ResponseBody
    public ResultResponse exceptionHandler(HttpServletRequest request, NumberFormatException formatException) {
        logger.error("发生类型转换异常, 原因是: ", formatException);
        return  ResultResponse.error(ExceptionEnum.PARAMS_NOT_CONVERT);
    }

    /**
     * 处理其他异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResultResponse exceptionHandler(HttpServletRequest request, Exception e)
    {
        logger.error("未知异常, 原因是: ",e);
        return  ResultResponse.error(ExceptionEnum.INTERNAL_SERVER_ERROR);
    }
}
